<?php

namespace app\home\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
use app\common\controller\Email;
use app\common\controller\Common;

/**
 * 运营计划明细列表管理
 * Class User
 * @package app\worker\controller
 */
class PlanDetail extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'PlanDetail';

    /**
     * 运营计划明细列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        //获取仓库表
        $where = [
            ['is_deleted', '=', 0],
            ['status', '=', 1],
        ];
        if(session('user.ware_house_id')){
            $where[] = ['id', '=', session('user.ware_house_id')];
         }
        $this->ware_house = Db::name('WareHouse')->where($where)->order('sort desc')->select();
        array_unshift($this->ware_house, ['id'=>0, 'name'=>'请选择仓库']);

        $this->title = '运营计划明细列表';
        $query = $this->_query($this->table)
            ->alias('pd')
            ->join('plan p', 'p.id = pd.plan_id', 'left')
            ->join('ware_house wh', 'wh.id = p.ware_house_id', 'left');
        if(session('user.ware_house_id')){
            $query->where('wh.id', session('user.ware_house_id'));
        }
        if(request()->get('plan_id')){
            $query->where('pd.plan_id', request()->get('plan_id'));
        }
        $query->order('pd.plan_id desc')
            ->field('pd.*,p.plan_date,wh.name as ware_house_name')
            ->page();
    }

    protected function _index_page_filter(&$data)
    {
        foreach($data as &$v){
            $v['users'] = Db::name('User')->whereIn('id', $v['uids'])->column('name');
            //主体名称
            $body_ids = Db::name('User')->whereIn('id', $v['uids'])->column('body_id');
            $body_ids = array_unique($body_ids);
            $body_ids = array_values($body_ids);
            $body_names = Db::name('Body')->whereIn('id', $body_ids)->column('body_name');
            $v['body_names'] = '';
            foreach($body_names as $vo){
                $v['body_names'] .= $vo.',';
            }
            if (mb_strlen($v['body_names'])>20) $v['body_names'] = mb_substr($v['body_names'],0,20) . '...';
        }
    }

     /**
     * 分派作业人员
     * @auth true
     */
    public function edit()
    {
        $this->_form($this->table, 'form');
    }

    public function _form_filter(&$data){
        if(request()->isPost()){
            if(empty($data['uids'])){
                $this->error('请选择作业人员');
            }
            if(count($data['content']['complete_count']) != $data['count']){
                $this->error('限定作业人员'.$data['count'].'个,请分配完整');
            }
            
            foreach($data['content']['complete_count'] as $k=>$v){
                $content[] = [
                    'complete_count' => $data['content']['complete_count'][$k],
                    'uid' => $data['content']['uid'][$k],
                    'name' => $data['content']['name'][$k],
                    'timeout_fine_price' => $data['content']['timeout_fine_price'][$k],
                    'goods_fine_price' => $data['content']['goods_fine_price'][$k],
                    'other_fine_price' => $data['content']['other_fine_price'][$k],
                ];
                $info[] = [
                    'complete_count' => $data['content']['complete_count'][$k],
                    'uid' => $data['content']['uid'][$k],
                    'timeout_fine_price' => $data['content']['timeout_fine_price'][$k],
                    'goods_fine_price' => $data['content']['goods_fine_price'][$k],
                    'other_fine_price' => $data['content']['other_fine_price'][$k],
                    'plan_detail_id' => $data['id'],
                ];
            }
            //添加运营计划明细用户关联信息
            Db::name('plan_detail_user')->where('plan_detail_id', $data['id'])->delete();//删除旧的
            Db::name('plan_detail_user')->insertAll($info);
           
            //再同步生成人员订单明细
            $info = [];
            $plan_detail = Db::name($this->table)->where('id', $data['id'])->find();
            foreach($content as $v){
                 //判断是否有订单，没有先生成订单
                $order_id = Db::name('Order')->where('uid', $v['uid'])->where('is_deleted', 0)->value('id');
                if(empty($order_id)){
                    $order_id = Db::name('Order')->insertGetId(['uid' => $v['uid']]);
                }
                $info[] = [
                    'plan_id' => $plan_detail['plan_id'],
                    'plan_detail_id' => $data['id'],
                    'order_id' => $order_id,
                    'price' => $plan_detail['price'],
                    'jobs' => $plan_detail['jobs'],
                    'complete_count' => $v['complete_count'],
                    'timeout_fine_price' => $v['timeout_fine_price'],
                    'goods_fine_price' => $v['goods_fine_price'],
                    'other_fine_price' => $v['other_fine_price'],
                ];
            }
            //如果已存在，修改完成件数
            $where = [
                'order_id' => $order_id,
                'plan_detail_id' => $data['id'],
            ];
            Db::name('OrderDetail')->where($where)->delete();//删除旧的  
            Db::name('OrderDetail')->insertAll($info);

            $data['content'] = json_encode($content);
        }
    }

    //获取运营计划列表
    public function getPlans(){
        $ware_house_id = request()->get('id');
        $plans = Db::name('Plan')
            ->where('is_deleted', 0)
            ->where('status', 1)
            ->where('ware_house_id', $ware_house_id)
            ->order('plan_date desc, create_at desc')
            ->select();
        $this->success('获取成功', $plans);
    }

    public function get_users()
    {
        //成员信息列表
        $where = [
            ['is_deleted', '=', 0],
            ['status', '=', 1],
        ];
        //过滤离职时间小于当前时间的数据
        $where[] = ['out_time', ['>=', date('Y-m-d')], ['=', ''], 'or'];
        //筛选对应 类型 分类 属性的人员
        $where[] = ['type', '=', request()->get('type')];
        $where[] = ['classify', '=', request()->get('classify')];
        $where[] = ['att', '=', request()->get('att')];
        if(session('user.ware_house_id')){
            $where[] = ['ware_house_id', '=', session('user.ware_house_id')];
        }
        $users = Db::name('User')->where($where)->order('create_at desc')->select();
        foreach($users as &$v){
            $res = Db::name('order_detail')
                ->alias('od')
                ->join('order o', 'o.id=od.order_id', 'left')
                ->where('od.plan_detail_id', request()->get('plan_detail_id'))
                ->where('o.uid', $v['id'])
                ->field('od.*')
                ->find();
            $v['complete_count'] = $res['complete_count'] ?? '';
            $v['timeout_fine_price'] = $res['timeout_fine_price'] ?? '';
            $v['goods_fine_price'] = $res['goods_fine_price'] ?? '';
            $v['other_fine_price'] = $res['other_fine_price'] ?? '';
            $v['body_name'] = Db::name('Body')->where('id', $v['body_id'])->value('body_name') ?? '';
            $v['name'] = $v['body_name'] . ' - ' . $v['name'];
        }
        $this->success('获取成功！', $users);
    }

     /**
     * 查看
     * @auth true
     */
    public function look(){
        $this->data = Db::name('plan_detail_user')
            ->alias('pdu')
            ->join('plan_detail pd', 'pd.id = pdu.plan_detail_id', 'left')
            ->join('user u', 'u.id = pdu.uid', 'left')
            ->join('body b', 'b.id = u.body_id', 'left')
            ->where('pd.id', request()->get('id'))
            ->field('u.name,pdu.complete_count,pd.price,b.body_name')
            ->select();
        $this->sum = 0;
        $this->sum_price = 0;
        foreach($this->data as $v){
            $this->sum += $v['complete_count'];
            $this->sum_price += $v['complete_count'] * $v['price'];
        }    
        $this->fetch();
    }
    /**
     * 台账
     * @auth true
     */
    public function order_detail_index(){}
}
